<!--
 * @Description: 新建/编辑充电站
 * @Author: py
 * @Date: 2024-02-24
-->
<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import { createOrUpdateStationApi } from '@fl/api/charge-settle'
import type { StationParams } from '@fl/api/charge-settle/model/station-model'
import { SubmitBtn } from '@fl/components'

import { useDicts } from '../hooks/use-dicts'

const props = withDefaults(defineProps<{
    formType?: string
    data?: any
    vendorOptions?: any[]
    vendorMap?: any
}>(), {
    formType: 'create',
    data: () => {},
    vendorOptions: () => [],
    vendorMap: () => {},
})

const emits = defineEmits(['success'])

const { getDictOptions } = useDicts()

const stationTypeOptions = getDictOptions('oStationType')

const { formType, data: rowData, vendorOptions, vendorMap } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<number | string>('id', { required: true })
const isDetailMode = computed(() => {
    return formType.value === 'detail'
})

const title = computed(() => {
    const titMap = {
        create: '新建充电站',
        edit: '编辑充电站',
        detail: '查看充电站',
    }
    return titMap[formType.value]
})

const formRef = ref()
const initialState = {
    stationName: '',
    stationId: '',
    stationType: '',
    vendorId: '',
    pileCount: undefined,
    directCount: undefined,
    alternatingCount: undefined,
}
const formValues = ref({ ...initialState })
const rules = {
    stationName: [{ message: '请输入充电站名称', required: true, trigger: 'blur' }],
    stationType: [{ message: '请选择充电站类型', required: true, trigger: 'change' }],
    vendorId: [{ message: '请选择合作商', required: true, trigger: 'change' }],
    pileCount: [{ message: '请输入桩数量', required: true, trigger: 'blur' }],
    directCount: [{ message: '请输入直流数', required: true, trigger: 'blur' }],
    alternatingCount: [{ message: '请输入交流数', required: true, trigger: 'blur' }],
}

const isFormLoading = ref(false)

watchEffect(() => {
    if (formType.value !== 'create' && rowData.value) {
        formValues.value = {
            ...rowData.value,
            stationType: rowData.value.stationType ?? '',
        }
    }
})

const isPending = ref(false)
// 提交
async function handleSubmit(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate(async (valid) => {
        if (valid) {
            const {
                stationName,
                stationId,
                stationType,
                vendorId,
                pileCount,
                directCount,
                alternatingCount,
            } = formValues.value
            let oParams: StationParams = {
                stationName,
                stationId,
                stationType,
                operatorId: '1',
                operatorName: '城服集团',
                vendorId,
                vendorName: vendorMap.value[vendorId],
                pileCount,
                directCount,
                alternatingCount,
            }

            // isFormLoading.value = true;

            try {
                if (formType.value === 'edit') {
                    oParams = {
                        ...oParams,
                        id: id.value,
                    }
                    await createOrUpdateStationApi(oParams)
                    ElMessage.success('编辑成功')
                }
                else {
                    await createOrUpdateStationApi(oParams)
                    ElMessage.success('新增成功')
                }

                visible.value = false
                emits('success')
            }
            catch (error) {
                console.error(error)
            }
            // finally {
            //     isFormLoading.value = false
            // }
        }
    })
}

// 取消
function handleCancel() {
    visible.value = false
}

// 重置
function handleReset(formEl: FormInstance | undefined) {
    id.value = ''
    formValues.value = { ...initialState }
    if (!formEl)
        return
    // formRef.value.formInstance.resetFields()
    formEl.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="1000"
                class="station-dialog"
                close-on-press-escape
                :has-footer="!isDetailMode"
                @cancel="handleCancel"
                @closed="handleReset(formRef)"
    >
        <ElSkeleton v-if="isFormLoading"
                    animated
        />

        <el-form v-else
                 ref="formRef"
                 :model="formValues"
                 :rules="rules"
                 label-position="top"
                 label-width="auto"
        >
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="充电站名称"
                                  prop="stationName"
                    >
                        <el-input v-model="formValues.stationName"
                                  placeholder="请输入"
                                  :disabled="formType === 'detail' || formType === 'edit'"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="充电站类型"
                                  prop="stationType"
                    >
                        <el-select v-model="formValues.stationType"
                                   :disabled="isDetailMode"
                        >
                            <el-option v-for="item in stationTypeOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属合作商名称"
                                  prop="vendorId"
                    >
                        <el-select v-model="formValues.vendorId"
                                   :disabled="isDetailMode"
                        >
                            <el-option v-for="item in vendorOptions"
                                       :key="item.dictValue"
                                       :label="item.dictLabel"
                                       :value="item.dictValue"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="桩数量"
                                  prop="pileCount"
                    >
                        <el-input-number v-model="formValues.pileCount"
                                         placeholder="请输入"
                                         class="input-num"
                                         :controls="false"
                                         :min="0"
                                         :precision="0"
                                         :disabled="isDetailMode"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="直流数"
                                  prop="directCount"
                    >
                        <el-input-number v-model="formValues.directCount"
                                         placeholder="请输入"
                                         class="input-num"
                                         :controls="false"
                                         :min="0"
                                         :precision="0"
                                         :disabled="isDetailMode"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="交流数"
                                  prop="alternatingCount"
                    >
                        <el-input-number v-model="formValues.alternatingCount"
                                         placeholder="请输入"
                                         class="input-num"
                                         :controls="false"
                                         :min="0"
                                         :precision="0"
                                         :disabled="isDetailMode"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="pr-32 ml-auto">
                <el-button @click="handleCancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="handleSubmit(formRef)"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>

<style lang="less">
.station-dialog {
    border-radius: 4px;
    overflow: hidden;
    padding: 56px 0 16px !important;

    .el-dialog__header {
        height: 56px !important;
        padding: 0 32px !important;
        line-height: 56px;

        .el-dialog__title {
            color: #1d2129;
        }

        .el-dialog__headerbtn {
            top: 50%;
            transform: translateY(-50%);
            right: 16px;
        }
    }

    .el-dialog__body {
        padding: 24px 32px 8px !important;
    }

    .el-form-item--default {
        margin-bottom: 16px;
    }

    .el-form-item__label {
        color: #1d2129;
    }

    .el-select__placeholder {
        color: #1d2129;

        &.is-transparent {
            color: #c9cdd4;
        }
    }

    .el-input__inner {
        color: #1d2129;

        &::placeholder {
            color: #c9cdd4;
        }
    }
}
</style>

<style lang="less" scoped>
@import '../../custom.less';

.input-num {
    width: 100%;

    :deep(.el-input__inner) {
        text-align: left;
    }
}
</style>
